package pe.com.pgn.consolidadorventas.servidorestacion.ws.security;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import pe.com.pgn.consolidadorventas.servidorestacion.ws.security.service.WsSeguridadService;

import com.sun.xml.wss.impl.callback.PasswordValidationCallback;

public class PlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { 
	
	static Logger logger = Logger.getLogger(PlainTextPasswordValidator.class);

	WsSeguridadService wsSeguridadService; 
	
	public PlainTextPasswordValidator(WsSeguridadService wsSeguridadService){
		this.wsSeguridadService=wsSeguridadService;
	}
	
 	public boolean validate(PasswordValidationCallback.Request request) throws PasswordValidationCallback.PasswordValidationException {
 		boolean resultado = false;
 		String contextPath = null;
 		String servletPath = null;
 		String ipRemota=null;
 		String hostRemoto=null;
		String codExtranet = null;
 		
 		PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest = (PasswordValidationCallback.PlainTextPasswordRequest) request;
 		
 		HttpServletRequest httpRequest = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
 		
 		contextPath = httpRequest.getContextPath();
 		servletPath = httpRequest.getServletPath();
 			
 		ipRemota = httpRequest.getRemoteAddr();
 		hostRemoto = httpRequest.getRemoteHost();

 		/*
 		if (logger.isDebugEnabled()) logger.debug("contexto " + contextPath);
 		if (logger.isDebugEnabled()) logger.debug("servletPath " + servletPath);
 		
 		if (logger.isDebugEnabled()) logger.debug("ipRemota : " + ipRemota);
 		if (logger.isDebugEnabled()) logger.debug("hostRemoto : " + hostRemoto);
 		*/
 		
 		imprimeInformacion("Intento de acceso desde ip:"+ipRemota+" , hostRemoto:"+hostRemoto+" , contexto:"+contextPath+" , servletPath:"+servletPath);
 		
 		long time = System.currentTimeMillis();
 		//if (logger.isDebugEnabled()) logger.debug("Usuario : " + plainTextRequest.getUsername());
 		//if (logger.isDebugEnabled()) logger.debug("Clave : " + plainTextRequest.getPassword());
 		
 		codExtranet = plainTextRequest.getUsername();
 		String password = plainTextRequest.getPassword();
 				
 		imprimeInformacion("Autenticacion de usuario : " + (System.currentTimeMillis()-time)+" ms");
 		
 		time = System.currentTimeMillis();
 		
 		resultado=wsSeguridadService.autenticar(ipRemota,servletPath,codExtranet, password);
 		
 		if(resultado){		
 			imprimeInformacion("Validacion de usuario exitosa : "+(System.currentTimeMillis()-time)+" ms");
 		}else{
 			imprimeError("Claves incorrectas");
 		}
 		
 		return resultado;
 	}
 	
 	private void imprimeInformacion(String accion){
		if(logger.isInfoEnabled()){ logger.info(accion); }
	}
	
	private void imprimeError(String error){
		logger.error(error);
	}
 	
}